//
//  LTY_ShakeViewController.m
//  MooMusic
//
//  Created by 守护神 on 15/10/25.
//  Copyright © 2015年 wjy. All rights reserved.
//

#import "LTY_ShakeViewController.h"
// 导入摇一摇自定义view
#import "LTY_ShakeView.h"
// 导入NetWork头文件
#import "NetWork.h"
// 导入摇一摇的model
#import "LTY_ShakeModel.h"

#import "TabBarController.h"
#define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
#define DEGREES_TO_RADIANS(d) (d * M_PI / 180)

@interface LTY_ShakeViewController ()

// 设置自定义view的属性
@property (nonatomic, strong)LTY_ShakeView *shakeView;
// 存放urlList的array
@property (nonatomic, strong)NSMutableArray *urlListArray;
@property (nonatomic, strong) TabBarController *tabBarSingle;
@end

NSInteger b;

@implementation LTY_ShakeViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //设置默认参数
    angle =30.0;
    timeInter = 0.05;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImage *backImage = [UIImage imageNamed:@"back.png"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage style:UIBarButtonItemStylePlain target:self action:@selector(backButton)];
    
    
    self.shakeView = [[LTY_ShakeView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH/2.0, SCREENWIDTH/2.0 + 30)];
    self.shakeView.center = CGPointMake(SCREENWIDTH/2.0, 228);
    [self.view addSubview:self.shakeView];
    
    
    // 摇一摇功能
    [[UIApplication sharedApplication] setApplicationSupportsShakeToEdit:YES];
    [self becomeFirstResponder];

    
    
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    
    //*************************设置气球的图层
    [self initLayer];
    
    
    // Do any additional setup after loading the view.
}

-(void)initLayer
{
    ballLayer=[CALayer layer];
    ballLayer.bounds = CGRectMake(0, 0, 128,128);
    ballLayer.position = CGPointMake(SCREENWIDTH/2, SCREENHEIGHT*0.8);
    if (IS_IPHONE_5) {
        ballLayer.contents = (id)[UIImage imageNamed:@"yaoyiyao.png"].CGImage;
    }else{
        ballLayer.contents = (id)[UIImage imageNamed:@"yaoyiyao"].CGImage;
    }
    ballLayer.anchorPoint = CGPointMake(0.5, 1.0);
    [self.view.layer addSublayer:ballLayer];
}


-(void)go
{
    btn.userInteractionEnabled = NO;
    
    
    //左右摇摆时间是定义的时间的2倍
    [NSTimer scheduledTimerWithTimeInterval:timeInter*2
                                     target:self
                                   selector:@selector(ballAnmation:)
                                   userInfo:nil
                                    repeats:YES];
}

-(void)ballAnmation:(NSTimer *)theTimer
{
    //设置左右摇摆
    angle=-angle;
    if (angle > 0) {
        angle--;
    }else{
        angle++;
    }
    CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat:(DEGREES_TO_RADIANS(angle))];
    rotationAnimation.duration = timeInter;
    rotationAnimation.autoreverses = YES; // Very convenient CA feature for an animation like this
    rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [ballLayer addAnimation:rotationAnimation forKey:@"revItUpAnimation"];
    if (angle == 0) {
        [theTimer invalidate];
        //动画完毕操作
        btn.userInteractionEnabled = YES;
        angle =30.0;
        timeInter = 0.05;
    }
}
//***************************************


- (BOOL)canBecomeFirstResponder
{
    return YES;// default is NO
}

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    // 检测到摇动
    NSLog(@"开始摇了");
    
}


- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    //摇动取消
    NSLog(@"摇动取消");
}


- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    // 实现气球的阻尼晃动
    [self go];
    
    
    // 获取数据
    [NetWork networkGETRequestWithURL:@"http://api.songlist.ttpod.com/ranklists/9/current?app=ttpod&v=v8.0.1.2015091618" Paramater:nil ResultBlock:^(id result) {
       
        //NSLog(@"+_+_+_+_+_  %@", result);
        NSMutableArray *songsArray = [NSMutableArray array];
        songsArray = [result objectForKey:@"songs"];
        // urlListArray
        self.urlListArray = [NSMutableArray array];
        
        NSMutableArray *modelArray = [NSMutableArray array];
        
        // 循环遍历数组
        for (NSDictionary *dic in songsArray) {
            LTY_ShakeModel *model = [[LTY_ShakeModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [modelArray addObject:model];
            // 把url存放到数组里
            if ([[dic objectForKey:@"urlList"] count] > 0) {
                
                [self.urlListArray addObject:[[[dic objectForKey:@"urlList"] objectAtIndex:0] valueForKey:@"url"]];
                
            }else{
                [self.urlListArray addObject:@"http://om32.alicdn.com/169/7169/422995/1770003520_1974919_l.m4a?auth_key=8be96137d126a30f4f66bec970c6b0b7-1446336000-0-null"];
            }
            
        }
        
        b = arc4random()%modelArray.count;
        self.shakeView.model = [modelArray objectAtIndex:b];
        NSString *string = [self.urlListArray objectAtIndex:b];
        

        
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shaketapAction)];
        [self.shakeView addGestureRecognizer:tap];

        
    }];
    
    

}

#pragma mark -- 返回按钮触发的方法
- (void)backButton
{
    [self.navigationController popToRootViewControllerAnimated:YES];
//    [self dismissViewControllerAnimated:YES completion:^{
    
        
//    }];
}

#pragma mark -- tap点击进入播放页面
- (void)shaketapAction
{
    NSLog(@"手势触发进入播放页面");
    NSString *string = [self.urlListArray objectAtIndex:b];
    NSLog(@"_____  %@", string);
    self.tabBarSingle = [TabBarController shareTabBar];
    self.tabBarSingle.array = [NSMutableArray array];
    self.tabBarSingle.array = [NSMutableArray arrayWithArray:self.urlListArray];
    
    //    self.tabBarSingle.imgName = [self.arr[indexPath.item] pic];
    self.tabBarSingle.index = self.urlListArray.count;
//        self.tabBarSingle.index = 0;
    [self.tabBarSingle.tabBarView.songStopORStart setImage:[UIImage imageNamed:@"pause"] forState:(UIControlStateNormal)];
    
    [self.tabBarSingle play:[self.urlListArray objectAtIndex:b]];
    
    // 更新tabBar内容
//    self.tabBarSingle.tabBarView.songerName.text = [self.dataArray[indexPath.row] singerName];
//    self.tabBarSingle.tabBarView.songName.text = [self.dataArray[indexPath.row] name];
    
    self.tabBarSingle.stopAngle = 10;
    [self.tabBarSingle startAnimation];

    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
